package com.gs.core.service.impl;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.support.JmsUtils;
import org.springframework.stereotype.Service;

import com.gs.core.domain.Order;
import com.gs.core.service.AlertService;

@Service
public class AlertServiceImpl implements AlertService {

	@Autowired
	JmsTemplate jmsTemplate;

	public void sendOrderAlert(final Order order) {
		// When the send() method is called, JmsTemplate will deal with
		// obtaining a JMS connection and session and will send the message on
		// behalf of the sender
		jmsTemplate.send("order.alert.queue", new MessageCreator() {

			public Message createMessage(Session session) throws JMSException {
				System.out.println("Sending order..");
				return session.createObjectMessage(order);
			}
		});
	}
	
	public Order getAlert(){
		try {
			ObjectMessage receivedMessage = (ObjectMessage) jmsTemplate.receive("order.alert.queue");
			return (Order) receivedMessage.getObject();
		} catch (JMSException e) {
			throw JmsUtils.convertJmsAccessException(e);
		}
	}

}
